// 合并零之间的节点
// https://leetcode.cn/problems/merge-nodes-in-between-zeros/description/
/**
 * Definition for singly-linked list.
 * function ListNode(val, next) {
 *     this.val = (val===undefined ? 0 : val)
 *     this.next = (next===undefined ? null : next)
 * }
 */

let ListNodeTool = require('./listNode');
let listNodeTool = new ListNodeTool();

/**
 * @param {ListNode} head
 * @return {ListNode}
 */
var mergeNodes = function (head) {
    let headNode = head.next;

    let nextNode = getNextNode(headNode);
    while (nextNode !== null) {
        nextNode = getNextNode(nextNode);
    }

    console.log(listNodeTool.flat(headNode));
    return headNode;
};

var getNextNode = function (current) {
    if (current.next === null) {
        return null;
    }

    let next = current.next;

    if (next.val !== 0) {
        current.val += next.val;
        current.next = next.next;
        return current;
    }

    current.next = next.next;
    return current.next;
};

let head = listNodeTool.listNode([0, 3, 1, 0, 4, 5, 2, 0]);

mergeNodes(head); // [4,11]

head = listNodeTool.listNode([0, 1, 0, 3, 0, 2, 2, 0]);
mergeNodes(head); // [1,3,4]
